package b2.scene.fight.skills
{
	import b2.scene.fight.PlayState;
	import b2.scene.fight.TankSprite;
	
	import flash.geom.Rectangle;

	public class TurnArround extends BasicSkill
	{
		private var direction:int;
		private var areas:Array;
		private var rememberDirection:int;
		private var range:int;
		
		public function TurnArround(tankId:int, tankSide:int ,level:int, skillArgs:Object)
		{
			super(tankId, tankSide ,level, skillArgs);
			var tank:TankSprite = getPlayState().tanks[tankId];
			areas = new Array();
			if (skillArgs.effectRange != null&&skillArgs.effectRange != 0)
				range = skillArgs.effectRange;
			else
				range = 13;
		}
		
		private function createPlayStaetRect(xTop:int, yTop:int, xBottom:int, yBottom:int):Rectangle
		{
			return new Rectangle(PlayState.OFFSET_X + xTop, PlayState.OFFSET_Y + yTop, PlayState.OFFSET_X + xBottom, PlayState.OFFSET_Y + yBottom);
		}
		
		public override function checkSkillTriggerPremise(x:int, y:int, direction:int):Boolean
		{
			if (!super.checkSkillTriggerPremise(x, y, direction))
				return false;
			
			if (areas.length == 0)
			{
				var skillArea:SkillArea;
				for (var i:int = 0; i < 4; i++)
				{
					skillArea = new SkillArea(x, y, i);
					skillArea.addArea(PlayState.TILE_WIDTH * range, 0, PlayState.TILE_WIDTH / 2, PlayState.TILE_WIDTH / 2);
					areas.push(skillArea);
				}
			}
			var remember:int = -1;
			var playerState:PlayState = getPlayState();
			for (i = 0; i < 4; i++)
			{
				for (var tankIdStr:String in playerState.tanks)
				{
					var playerTank:TankSprite = playerState.tanks[tankIdStr];
					if (playerTank.tankId > 0 && ((areas[i] as SkillArea).contain(playerTank.x + 2, playerTank.y + 2) || (areas[i] as SkillArea).contain(playerTank.x + PlayState.TILE_WIDTH - 2, playerTank.y + PlayState.TILE_WIDTH - 2)))
					{
						if (direction == i)
						{
							return false;
						}
						else 
						{
							remember = i;
						}
					}
				}
				
			}
			if (remember == -1)
				return false;
			else
			{
				rememberDirection = remember;
				return true;
			}
			return super.checkSkillTriggerPremise(x, y, direction);
		}
		
		public override function discharge(x:int, y:int, direction:int):void
		{
			getPlayState().updateTankDirection(tankId, rememberDirection);
			coolDown = 1;
		}
	}
}